package com.zhentao.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.es.service.ApArticleService;
import com.zhentao.es.mapper.ApArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.es.vo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApArticleMapper articleMapper;
    @Override
    public ResponseResult esInit() throws IOException {
        //1.查询出需要导入es的文章
        List<ApArticle> apArticles = articleMapper.selectList(null);
        //2.批量导入es
        BulkRequest bulkRequest=new BulkRequest("app_info_article");
        for (ApArticle apArticle : apArticles) {
            SearchArticleVo searchArticleVo=new SearchArticleVo();
            BeanUtils.copyProperties(apArticle, searchArticleVo);
            String string = JSON.toJSONString(searchArticleVo);
            IndexRequest indexRequest=new IndexRequest().id(searchArticleVo.getId()+"").source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return ResponseResult.okResult("导入成功："+apArticles.size());
    }
}
